// Learn cc.Class:
//  - https://docs.cocos.com/creator/manual/en/scripting/class.html
// Learn Attribute:
//  - https://docs.cocos.com/creator/manual/en/scripting/reference/attributes.html
// Learn life-cycle callbacks:
//  - https://docs.cocos.com/creator/manual/en/scripting/life-cycle-callbacks.html
var ClickManager = require('ClickManager')
var NetworkManager = require('NetworkManager')
var UnitTools = require('UnitTools')
var UserManager = require('UserManager')

cc.Class({
    extends: cc.Component,

    properties: {
        createTableNode: cc.Node,
        createBtn: cc.Node, // 创建按钮
        inningsToggle: cc.ToggleContainer,   // 局数选择
        numberToggle: cc.ToggleContainer,    // 人数选择
        minBalance: cc.EditBox, // 最低余额
        lowGrade: cc.EditBox,   // 下注低砖
        seniorChecks: {
            type: cc.Toggle,
            default: []
        },

        createTableData: {
            type: Object,
            default: {}
        },

        alertPrefab: cc.Prefab,
        token: null
    },

    // LIFE-CYCLE CALLBACKS:

    onLoad () {
        this.token = cc.sys.localStorage.getItem('__TOKEN__')
        this.pnode = cc.find('Canvas')

        ClickManager.onClick(this.createBtn, this, () => {
            this.doCreateTeble()
        })
    },

    onEnable () {
        this.init()
    },

    start () {

    },

    // 创建桌子
    doCreateTeble () {
        // 设置局数参数
        for (let i in this.inningsToggle.toggleItems) {
            let inningsItem = this.inningsToggle.toggleItems[i]
            if (inningsItem.isChecked) {
                this.createTableData.innings = i
            }
        }

        // 设置人数参数
        for (let i in this.numberToggle.toggleItems) {
            let numberItem = this.numberToggle.toggleItems[i]
            if (numberItem.isChecked) {
                this.createTableData.number = i
            }
        }

        // 设置高级参数
        for (let i in this.seniorChecks) {
            console.log(this.seniorChecks[i].isChecked)
            if (!this.seniorChecks[i].isChecked) {
                if (i == 0) {
                    this.createTableData.is_send_voice = 1
                } else if (i == 1) {
                    this.createTableData.is_send_text = 1
                }
            } else {
                if (i == 0) {
                    this.createTableData.is_send_voice = 0
                } else if (i == 1) {
                    this.createTableData.is_send_text = 0
                }
            }
        }

        this.createTableData.min_balance = this.minBalance.string
        this.createTableData.low_grade = this.lowGrade.string

        let rid = ClickManager.ccGetCache('__RID__')
        if (UnitTools.isNullOrUndefined(rid)) {
            ClickManager.alertModel(this.alertPrefab, '获取联盟失败，不可创建牌桌')
            return false
        }
        this.createTableData.rid = rid
        let sendData = JSON.stringify(this.createTableData)

        try {
            NetworkManager.onConnectedToHall( (hallService) => {
                hallService.proxy.createTable(this.token, sendData, (data) => {
                    this.createTableNode.active = false
                    if (data.code === 0) {
                        ClickManager.alertModel(this.alertPrefab, data.msg)
                    } else if (data.code === 200) {
                        // 创建成功，提示信息并更新用户数据
                        this.tableId = data.tid
                        ClickManager.alertModel(this.alertPrefab, data.msg)
                        NetworkManager.updateUserInfo()
                        this.linkTableServer()
                    } else {
                        ClickManager.alertModel(this.alertPrefab, '创建失败')
                    }
                })
            })
        } catch (err) {
            cc.director.loadScene('loading')
        }
    },

    // 加入牌桌
    joinTable () {
        var token = UserManager.token
        ClickManager.loading(this.pnode, '加入游戏牌桌中..')
        NetworkManager.onConnectedToGame((gameService) => {
            gameService.proxy.joinGameTable(token, this.tableId, (data) => {
                cc.log('加入游戏牌桌:', data)
                this.linkStatus = false
                if ((data.ok && data.code === 200) || data.code === 201) {
                    UserManager.tid = data.tid

                    ClickManager.loading(this.pnode, '加入游戏牌桌成功...')
                    cc.director.preloadScene('table',  this.onProgress.bind(this), () => {
                        if (!this.tableScene) {
                            cc.director.loadScene('table')
                            ClickManager.rmLoading(this.pnode)
                            this.tableScene = true
                        }
                    })
                } else if (data.ok && data.code === 0) {
                    ClickManager.rmLoading(this.pnode)
                    ClickManager.alertModel(this.alertModel, data.msg)
                } else if (!data.ok) {
                    ClickManager.rmLoading(this.pnode)
                    NetworkManager.onCloseFormGame()
                }
            })
        })
    },

    // 连接牌桌服务器
    linkTableServer () {
        ClickManager.loading(this.pnode, '连接游戏服务器中...')
        if (!NetworkManager.gGameServerIsLogin) {
            NetworkManager.connectAndAuthToGame()
        }
        NetworkManager.onConnectedToGame(() => {
            var loginData = UserManager.loginToGameData
            cc.log('连接游戏服务器:', loginData)
            if (loginData.isInGame) {
                ClickManager.loading(this.pnode, '连接游戏服务器成功...')
                this.joinTable()
            } else {
                // 不在游戏服务器，登录失败
                NetworkManager.clearGameService()
                ClickManager.rmLoading(this.pnode)
                ClickManager.alertModel(this.alertModel, '连接游戏服务器失败')
            }
        })
    },

    // 加载进度
    onProgress (com, total, item) {
        if (total < 10) {
            total = this.initTotal
        }

        let progress = com / total
        progress = isNaN(progress) ? 0 : progress
        ClickManager.loading(this.pnode, '游戏场景加载中('+ (progress*100).toFixed(2) +'%)...')
    },

    // 初始化信息
    init () {
        this.inningsToggle.node.children[1].getComponent(cc.Toggle).check()
        this.numberToggle.node.children[3].getComponent(cc.Toggle).check()
    }

    // update (dt) {},
});
